<?php
class WeMsg {
	public $msgType = "";
	public function WeMsg() {
		$postStr = file_get_contents ( "php://input" );
		// extract post data
		if (! empty ( $postStr )) {
			/*
			 * libxml_disable_entity_loader is to prevent XML eXternal Entity Injection, the best way is to check the validity of xml by yourself
			 */
			libxml_disable_entity_loader ( true );
			$postObj = simplexml_load_string ( $postStr, 'SimpleXMLElement', LIBXML_NOCDATA );
		} else
			throw new Exception ( "Error Load postStr", 1 );
	}
}

class WeChat
{
	private $_token = "";
	private $_appid = "";
	private $_appsecret = "";
	public $msg;
	public function WeChat()
	{
	}

	public function WeChat($token)
	{
		$_token = $token;
		if(!$this->_checkSignature())
			die("Wrong TOKEN");
		if(isset($_GET["echostr"]))
			die($_GET["echostr"]);
		$msg = WeMsg();
	}

	private function _checkSignature()
	{
        // you must define TOKEN by yourself
        if ($this->_token=="") {
            throw new Exception('TOKEN is not defined!');
        }
        
        $signature = $_GET["signature"];
        $timestamp = $_GET["timestamp"];
        $nonce = $_GET["nonce"];
        		
		$token = $this->_token;
		$tmpArr = array($token, $timestamp, $nonce);
        // use SORT_STRING rule
		sort($tmpArr, SORT_STRING);
		$tmpStr = implode( $tmpArr );
		$tmpStr = sha1( $tmpStr );
		
		if( $tmpStr == $signature ){
			return true;
		}else{
			return false;
		}
	}



?>